/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package uit.tkorg.coauthorgraph.servlet.importdb;

import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import uit.tkorg.coauthorgraph.bo.AuthorBO;
import uit.tkorg.coauthorgraph.bo.AuthorPaperBO;
import uit.tkorg.coauthorgraph.bo.ConferenceBO;
import uit.tkorg.coauthorgraph.bo.JournalBO;
import uit.tkorg.coauthorgraph.bo.PaperBO;
import uit.tkorg.coauthorgraph.dto.AuthorDTO;
import uit.tkorg.coauthorgraph.dto.ConferenceDTO;
import uit.tkorg.coauthorgraph.dto.JournalDTO;
import uit.tkorg.coauthorgraph.dto.PaperDTO;

/**
 *
 * @author Huynh Ngoc Tin
 */
/**
 * Servlet implementation class ImportPublicationServlet
 */
public class ImportPublicationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public ImportPublicationServlet() {
        super();
    }

    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Import the list of selected publications into the DB
        HttpSession session = request.getSession();
        ArrayList publicationList = (ArrayList) session.getAttribute("publicationList");
        String selectedPaperListStr = request.getParameter("selectedPaperListStr");
        if ((selectedPaperListStr != null) && (!selectedPaperListStr.equals(""))) {
            String[] selectedPaperIDList = selectedPaperListStr.split("#");
            ArrayList listImportedPaperDTO = new ArrayList();
            int currentIndex = 0;
            for (int i=0; i<selectedPaperIDList.length; i++) {
                currentIndex = Integer.parseInt(selectedPaperIDList[i]);
                listImportedPaperDTO.add((PaperDTO)publicationList.get(currentIndex));
            }

            try {
                PaperBO paperBO = new PaperBO();
                AuthorBO authorBO = new AuthorBO();

                PaperDTO paperDTO;
                // Import the metadata information for all selected papers that crawled from MAS
                for (int i=0; i<listImportedPaperDTO.size(); i++) {
                    paperDTO = (PaperDTO) listImportedPaperDTO.get(i);
                    if (!paperBO.isPaperExisted(paperDTO)) {
                        // insert a new paper into the 'paper' table
                        int insertPaperID = paperBO.insertNewPaper(paperDTO);

                        // insert authors into the tables ('author', 'authorinstance', 'authorpaper')
                        ArrayList authors = paperDTO.getAuthorNameList();
                        for (int j=0; j<authors.size(); j++) {
                            String authorName = (String) authors.get(j);
                            authorName = authorName.replaceAll("(\r\n|\r|\n|\n\r)", "");
                            int authorID = authorBO.getAuthorID(authorName);
                            if (authorID == -1) { // not exist in the 'Author' Table
                                // update information for authorDTO object
                                AuthorDTO authorDTO = new AuthorDTO();
                                authorDTO.setAuthorName(authorName);
                                authorID = authorBO.insertNewAuthor(authorDTO);
                            }

                            // insert authorID, paperID into the 'AuthorPaper' table
                            AuthorPaperBO author_paper_BO = new AuthorPaperBO();
                            int author_OrderNum = j+1;
                            author_paper_BO.insertNewAuthorPaper(authorID, insertPaperID, author_OrderNum);
                        }

                        // insert conferences
                        String confName = paperDTO.getConferenceName();
                        if (confName != null && !confName.equalsIgnoreCase("")) {
                            ConferenceBO confBO = new ConferenceBO();
                            ConferenceDTO confDTO = new ConferenceDTO();
                            confDTO.setConferenceName(confName);
                            confDTO.setYear(paperDTO.getYear());
                            int confID = confBO.getConferenceID(confName, paperDTO.getYear());
                            if (confID == -1) {
                                confBO.insertNewConference(confDTO);
                            }
                            else {
                                // this paper relate to a conference that existed inDB
                                // update confID cho bai bao dang xet --> paper table
                            }
                        }

                        // insert journals
                        String journalName = paperDTO.getJournalName();
                        if (journalName != null && !journalName.equalsIgnoreCase("")) {
                            JournalBO journalBO = new JournalBO();
                            JournalDTO journalDTO = new JournalDTO();
                            journalDTO.setJournalName(journalName);
                            journalDTO.setYear(paperDTO.getYear());
                            int journalID = journalBO.getJournalID(journalName, paperDTO.getYear());
                            if (journalID == -1) {
                                journalBO.insertNewJournal(journalDTO);
                            }
                            else {
                                // this paper relate to a journal that existed inDB
                                // update journalID cho bai bao dang xet --> paper table
                            }
                        }

                        // insert keywords
                    }

                    // remove the inserted paper out of the list to view the remain papers
                    publicationList.remove(paperDTO);
                } // end of for()
            }
            catch (Exception ex) {
                ex.printStackTrace();
            }
        }

        // Forward to CrawlFromMAS.jsp page
        session.removeAttribute("publicationList");
        session.setAttribute("publicationList", publicationList);
        request.setAttribute("actionResult", "Imported Success");
        RequestDispatcher dispatcher = request.getRequestDispatcher("./jsp/CrawlFromMAS.jsp");
        dispatcher.forward(request, response);
    }


}